package com.xgure.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.xgure.properties.JwtProperties;
import com.xgure.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * JWT用户拦截器
 */
@Component
public class JwtUserInterceptor implements HandlerInterceptor {

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 验证获取的token是否合法
        try {
            String token = request.getHeader(jwtProperties.getHeader());
            DecodedJWT decodedJWT = jwtUtil.verifyToken(token, jwtProperties.getSecretKey());
            // 放行
            return true;
        } catch (Exception ex) {
            // 不放行
            response.setStatus(401);
            return false;
        }
    }

}
